<template>
  <div id="tdtMapDivID" style="width: 100%; height: 100%;padding-top: 24px"></div>
  <!-- <img src="./mapimg/green.png" alt=""> -->
  <el-dialog v-model="livedialogVisible" :width="640" center>
    <div style="height: 300px;" v-if="livedialogVisible">
      <LivePlayer :videoUrl="flvUrl" fluent autoplay live stretch dblclick-fullscreen hide-stretch-button
                  hide-fullscreen-button aspect='fullscreen'>
        <span @click="livedialogVisible = false"
              style="position: absolute;top: 10px;right: 10px;cursor: pointer">X</span>
      </LivePlayer>
    </div>
  </el-dialog>
</template>

<script>
import useView from "@/hooks/useView";
import {defineComponent, reactive, toRefs} from "vue";
import baseService from "@/service/baseService";
import LivePlayer from "@liveqing/liveplayer-v3";
import Sensor from "@/views/workScreen/rightbox/sensor.vue";
import app from "@/constants/app";

export default defineComponent({
  name: "MapDiv",
  components: {
    LivePlayer,
    Sensor
  },
  setup() {
    const state = reactive({
      map: null,
      mapdata: [],
      TMaplnglats: [],
      mapLngLat: {},
      livedialogVisible: false,
      flvUrl: "",
      markreData: {},
      getMapDataId: null
    });


    return {...useView(state), ...toRefs(state)};
  },
  created() {
    this.getMapData();
  },
  mounted() {
    window.playflv = this.playflv;
    this.initMap();
    this.clearLbMapDataId();
    this.getMapDataId = setInterval(() => {
      this.getMapDatast();
    }, 1000 * 10);
    console.log(this.getMapDataId)
  },
  unmounted() {
    this.clearLbMapDataId();
  },
  methods: {
    clearLbMapDataId() {
      if (this.getMapDataId) {
        clearInterval(this.getMapDataId);
      }
    },
    getMapDatast() {
      baseService.get("/KxStation/kxstation/getMapList").then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        this.mapdata = res.data;

        this.map.clearOverLays();
        this.intiAddMarskst();
      });
    },
    // 地图数据
    getMapData() {
      baseService.get("/KxStation/kxstation/getMapList").then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        this.mapdata = res.data;
        // this.mapdata.forEach((row) => {
        //   this.mapLngLat[row.id] = {lat: row.lat84, lng: row.lng84};
        // });

        this.intiAddMarsk();
      });
    },
    /**
     * 初始化地图
     * @param {*} lng 经度
     * @param {*} lat 纬度
     * @param {*} zoom 缩放比例(1~18)
     **/
    initMap() {
      let T = window.T;
      //地图实例
      this.map = new T.Map("tdtMapDivID");
      // 去掉水印
      document.getElementsByClassName("tdt-control-copyright tdt-control")[0].style.display = "none";
      //创建卫星和路网的混合视图
      this.map.setMapType(window.TMAP_HYBRID_MAP);
      this.map.centerAndZoom(new T.LngLat(103.388611, 35.563611), 5);
    },
    intiAddMarskst() {
      // 加载点位图标
      if (this.mapdata != null && this.mapdata.length > 0) {
        let maxl = this.mapdata[0].lng84,
            minl = this.mapdata[0].lng84,
            maxb = this.mapdata[0].lat84,
            minb = this.mapdata[0].lat84;
        for (var i = 0; i < this.mapdata.length; i++) {
          this.TMaplnglats.push(new T.LngLat(this.mapdata[i].lng84, this.mapdata[i].lat84));
          this.addMarker(this.mapdata[i], T, false);

          if (this.mapdata[i].lng84 === null || this.mapdata[i].lat84 === null) {
            continue;
          }
        }
      } else {
        //没有坐标，显示全中国
        this.map.centerAndZoom(new T.LngLat(103.388611, 35.563611), 5);
      }

      this.$emit("maprefresh");
    },
    intiAddMarsk() {
      // 加载点位图标
      if (this.mapdata != null && this.mapdata.length > 0) {
        let maxl = this.mapdata[0].lng84,
            minl = this.mapdata[0].lng84,
            maxb = this.mapdata[0].lat84,
            minb = this.mapdata[0].lat84;
        for (var i = 0; i < this.mapdata.length; i++) {
          this.TMaplnglats.push(new T.LngLat(this.mapdata[i].lng84, this.mapdata[i].lat84));
          this.addMarker(this.mapdata[i], T, false);

          if (this.mapdata[i].lng84 === null || this.mapdata[i].lat84 === null) {
            continue;
          }

          // if (this.mapdata[i].lng84 > maxl) maxl = this.mapdata[i].lng84;
          // if (this.mapdata[i].lng84 < minl) minl = this.mapdata[i].lng84;
          // if (this.mapdata[i].lat84 > maxb) maxb = this.mapdata[i].lat84;
          // if (this.mapdata[i].lat84 < minb) minb = this.mapdata[i].lat84;
        }

        // let cenLng = (parseFloat(maxl) + parseFloat(minl)) / 2;
        // let cenLat = (parseFloat(maxb) + parseFloat(minb)) / 2;
        // let zoom = this.getZoom(maxl, minl, maxb, minb);
        // console.log(cenLng , cenLat, zoom)
        // this.map.centerAndZoom(new T.LngLat(cenLng, cenLat), zoom);
      } else {
        //没有坐标，显示全中国
        // this.map.centerAndZoom(new T.LngLat(103.388611, 35.563611), 5);
      }
      this.$emit("mapInit");
    },
    // 计算地图缩放比例
    getZoom(maxLng, minLng, maxLat, minLat) {
      var zoom = ["50", "100", "200", "500", "1000", "2000", "5000", "10000", "20000", "25000", "50000", "100000", "200000", "500000", "1000000", "2000000"]//级别18到3。
      var pointA = new T.LngLat(maxLng, maxLat);  // 创建点坐标A
      var pointB = new T.LngLat(minLng, minLat);  // 创建点坐标B
      var distance = this.map.getDistance(pointA, pointB).toFixed(1);  //获取两点距离,保留小数点后两位
      for (var i = 0, zoomLen = zoom.length; i < zoomLen; i++) {
        if (zoom[i] - distance > 0) {
          return 18 - i + 3;//之所以会多3，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。
        }
      }
    },
    // 查找id对应信息
    findMarsk(id) {
      for (let item of this.mapdata) {
        if (item.id === id) {
          this.markreData = item
          break;
        }
      }
      if (this.markreData.lng84 != null && this.markreData.lat84 != null) {
        this.marsktu(this.markreData.lng84, this.markreData.lat84)
      } else {
        this.$message.warning(this.markreData.name + "杆塔暂无坐标信息！");
      }
    },
    // 点位寻找
    marsktu(lng, lat) {
      let T = window.T;
      // this.map.clearOverLays();
      this.map.centerAndZoom(new T.LngLat(lng, lat), 16);
      // 定义该矩形的显示区域
      let circle = new T.Circle(new T.LngLat(lng, lat), 40, {
        color: "red",
        weight: 3,
        opacity: 0.5,
        fillColor: "#FFFFFF",
        fillOpacity: 0.1,
        lineStyle: "solid"
      });
      //向地图上添加圆
      // this.map.addOverLay(circle);
      this.addMarker(this.markreData, T, true);
    },
    addMarker(markdata, T, flag) {
      let marker;
      let icon;
      let point;
      let url0 = "/mapimg/inf.png"; //离线
      let url1 = "/mapimg/green.png"; //在线
      let url2 = "/mapimg/red.png"; //报警
      // let url2 = "/mapimg/notice.png"; //报警
      if (markdata.status === "offline") {
        // 离线
        icon = new T.Icon({
          iconUrl: url0,
          iconSize: new T.Point(50, 50),
          iconAnchor: new T.Point(15, 52)
        });
      } else if (markdata.status === "normal") {
        //正常
        icon = new T.Icon({
          iconUrl: url1,
          iconSize: new T.Point(50, 50),
          iconAnchor: new T.Point(15, 52)
        });
      } else {
        //报警
        icon = new T.Icon({
          iconUrl: url2,
          iconSize: new T.Point(50, 50),
          iconAnchor: new T.Point(15, 52)
        });
      }

      point = new T.LngLat(markdata.lng84, markdata.lat84);
      marker = new T.Marker(point, {icon: icon}); // 创建标注

      // if(!flag){
      this.map.addOverLay(marker); // 将标注添加到地图中
      // }

      // 相机
      let flvbuttone = ""
      if (markdata.cameraDTOS != null) {
        markdata.cameraDTOS.forEach((item) => {
          flvbuttone = `<button style="margin-right: 6px" onclick=playflv(${JSON.stringify(item)})>${item.name}</button>` + flvbuttone
        })
      }

      // 报警数量
      let bajingtext = ""
      bajingtext = `<p style="margin-right: 0" >图片告警数：<span style="color: red;font-size: 16px">${markdata.imgNum}</span></p><p style="margin-right: 0" >传感器告警数：<span style="color: red;font-size: 16px">${markdata.sensorNum}</span></p>`


      // 工作状态
      // <div style="display: flex;margin: 0">
      //   <p style="flex: 1;margin: 0">工作总时间：${markdata.statusDTO.totalWorkingTime}H</p>
      //   <p style="flex: 1;margin: 0">连续工作时间：${markdata.statusDTO.workingTime}H</p>
      // </div>
      // <div style="display: flex;margin: 0">
      //   <p style="flex: 1;margin: 0">网络连接状态：${ markdata.statusDTO.connectionState }</p>
      // </div>
      let wrokdiv = ""

      // ${wrokdiv}
      if (markdata.statusDTO != null) {
        wrokdiv = `<div>
          <h3 style="margin: 0;color: #ffcc00">工作状态&nbsp;&nbsp;&nbsp;<span style="color: #fff;font-size: 12px">${markdata.statusDTO.timeStamp}</span></h3>
          <div style="display: flex;margin: 0">
               <p style="flex: 1;margin: 0">电源电压：${markdata.statusDTO.batteryVoltage}V</p>
               <p style="flex: 1;margin: 0">工作温度：${markdata.statusDTO.operationTemperature}℃</p>
          </div>
          <div style="display: flex;margin: 0">
               <p style="flex: 1;margin: 0">电池电量：${markdata.statusDTO.batteryCapacity}%</p>
               <p style="flex: 1;margin: 0">浮充状态：${markdata.statusDTO.floatingCharge == '00' ? '放电' : '充电'}</p>
           </div>
        </div>`
      }


      let content = ` <div class="xxdiv">
        <p style="font-size: 16px; text-align:center;color: #fff; font-weight:bold; margin: 0px; margin-bottom: 10px">${markdata.name}</p>
        <p style="color: #fff; margin: 4px 0px 4px 0px;">
          <span style="color: #fff;">经度：${markdata.lng}</span>
          <span style="color:#fff; margin-left: 10px;"> 纬度：${markdata.lat}</span>
        </p>
        ${bajingtext}
        <p style="margin: 10px 0">${flvbuttone}</p>
      </div>`;
      if (flag) {
        let markerInfoWin = new T.InfoWindow();
        markerInfoWin.setContent(content);
        marker.openInfoWindow(markerInfoWin, point); // 开启信息窗口
      }

      // 双击开启信息窗口
      // dblclick
      marker.addEventListener("click ", function () {
        let markerInfoWin = new T.InfoWindow();
        markerInfoWin.setContent(content);
        marker.openInfoWindow(markerInfoWin, point);
      });

      // 移入开启信息窗口
      // marker.addEventListener("mousedown ", function () {
      //   // let id = markdata.children ? markdata.children[0].id : markdata.id;
      //   let markerInfoWin = new T.InfoWindow();
      //   markerInfoWin.setContent(content);
      //   marker.openInfoWindow(markerInfoWin, point);
      // });

      // 关闭信息窗口
      // marker.addEventListener("mouseup ", function () {
      //   let markerInfoWin = new T.InfoWindow();
      //   markerInfoWin.setContent(content);
      //   marker.closeInfoWindow(markerInfoWin, point);
      // });
    },
    playflv(data) {
      this.livedialogVisible = true;
      this.flvUrl = app.httpgbflv + data.gbFlv;
    },
    loadText() {
      let T = window.T;
      if (this.mapdata.length != 0) {
        this.mapdata.forEach((item) => {
          let labelName = item.sName;
          if (item) {
            labelName = labelName.replace("GDLNG-", "");
          }
          let config = {
            text: labelName,
            offset: new T.Point(-45, -65),
            position: new T.LngLat(item.lng84, item.lat84)
          };
          let label = new T.Label(config);
          label.setFontColor("#fff");
          // label.setFontSize();
          label.setBackgroundColor("transparent");
          label.setBorderColor("transparent");
          // label.setAnchorPer([0.5, 0]); //偏移量
          // label.setBorderLine(0); //设置文本的边框线宽。
          // label.setFontColor("#fff"); //设置文本的边框线宽。
          // label.setOpacity(0); //设置文本的边框线宽。
          this.map.addOverLay(label);
        });
      }
    }
  }
});
</script>

<style lang="scss" scoped>
.xxdiv {
  //background-color: rgba($color: #000000, $alpha: 0.3);
  z-index: 899;
}

.tdt-infowindow-content-wrapper,
.tdt-infowindow-tip {
  //background: #535151 !important;
  border-radius: 20px !important;
}

::v-deep .tdt-infowindow-content-wrapper {
  font-family: Source Han Sans CN;
  font-weight: 500;
  font-size: 12px;
  color: #FFFFFF;
  background-color: transparent;
  background-image: url("../../../../public/mapimg/mapxx_bj.png");
  background-size: 100% 100%;
}
</style>
